package com.example.filedownload;

import cn.hutool.core.io.FileUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class OkHttpDownloadExample {

    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpDownloadExample.class);

    private static final OkHttpClient client = new OkHttpClient();

    public static void downloadFile(String urlStr, String targetFilePath) throws IOException {
        Request request = new Request.Builder()
                .url(urlStr)
                // 可以根据需要添加断点续传的支持，通过设置Range头
                // .header("Range", "bytes=" + start + "-" + end)
                .build();

        try (Response response = client.newCall(request).execute();
             InputStream inputStream = response.body().byteStream();
             FileOutputStream outputStream = new FileOutputStream(targetFilePath, /*append=*/true)) {

            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            byte[] buffer = new byte[8 * 1024]; // 8KB缓冲区
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
        }
    }

    public static void main(String[] args) {
        String url = "http://localhost:8080/download/ubuntu-20.04.4-desktop-amd64.iso";
        String savePath = "D:/temp/download/ubuntu-20.04.4-desktop-amd64.iso";

        try {
            FileUtil.del(new File(savePath));
            LOGGER.info("文件下载开始...");
            downloadFile(url, savePath);
            LOGGER.info("文件下载完成...");
        } catch (IOException e) {
            LOGGER.error("下载失败: " + e.getMessage());
        }
    }
}
